package game;

import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public abstract class MenuSlider extends MenuItem{
	private static final long serialVersionUID = 1L;
	private Rectangle slider;
	protected BufferedImage normal = getImage(new File("images/lrbutton.png"));
	protected BufferedImage sliderImage = getImage(new File("images/slider.png"));
	protected int maxX;
	protected int minX;
	private String pString;
	protected boolean held;
	protected float value;
	protected int offset;
	protected TextLayout textLayout;
	
	public MenuSlider(Menu m, int x, int y, int w, int h, String content, int fontSize){
		super(m, x, y, w, h, content, fontSize);
		slider = new Rectangle(x + width/2, y, 20, height);
		maxX = x + width - 20;
		minX = x;
		held = false;
	}
	
	protected void draw(){
		host.getCanvas().bufGraphics.setColor(Color.black);
		textLayout = new TextLayout(info+" "+pString, font, host.canvas.bufGraphics.getFontRenderContext());
		host.getCanvas().bufGraphics.drawImage(normal, x, y, width, height, host.getCanvas());
		host.getCanvas().bufGraphics.drawRect(x, y, width, height);
		host.canvas.bufGraphics.setColor(Color.black);
		host.canvas.bufGraphics.setFont(font);
		textLayout.draw(host.canvas.bufGraphics, x+(int)(this.width-textLayout.getBounds().getWidth())/2, y+(int)(this.height+textLayout.getBounds().getHeight())/2);
		host.canvas.bufGraphics.setColor(Color.black);
		host.getCanvas().bufGraphics.drawImage(sliderImage, slider.x, slider.y, slider.width, height, host.getCanvas());
		host.getCanvas().bufGraphics.drawRect(slider.x, slider.y, slider.width, height);
	}
	
	public void update(){
        pString = Math.round(getPosition() * 100) + "%";
        if(held){
        	setValue(host.getCanvas().mousePos.x-offset);
        }
        if(value < 0){
			slider.x = minX;
		}else if(value > 1){
			slider.x = maxX;
		}else{
			slider.x = (int)((maxX-minX)*value + minX);
		}
	}
	
	protected void setValue(int i){
	    value = (float)(i-minX)/(maxX-minX);
	    if(value > 1){
	    	value = 1;
	    }else if(value < 0){
	    	value = 0;
	    }
	}
	
	public void clicked(MouseEvent e){
		if(slider.contains(new Point(e.getX(), e.getY()))){
			offset = e.getX()-slider.x;
			held = true;
		}
	}
	
	public void released(MouseEvent e){
		held = false;
	}
	
	protected void setValue(float f){
		value = f;
	}
	
	protected float getPosition(){
	    return value;
	}
	
	public BufferedImage getImage(File f){
		try{
			return ImageIO.read(f);
		}catch (IOException e){
			return null;
		}
	}
}
